﻿@using Smartstore.Core.Web;
@using Smartstore.Utilities;

@model ChoiceModel

@inject IWebHelper WebHelper

@{
    // TODO: (mh) (core) Customers uploaded product variant file is lost after selecting any other variant option (in product details).
    var storeUrl = WebHelper.GetStoreLocation(false);
    var controlId = Model.BuildControlId();
    var clientId = "upload" + CommonHelper.GenerateRandomInteger();
    var containerId = clientId + "container";
    var allowedFileExtensions = string.Join("|", Model.AllowedFileExtensions.Select(x => x.Trim()).ToList());
}

<div id="@containerId">
    <div class="fu-container">
        <div class="dropzone-container">
            <div class="fu-thumb fu-filename rounded" data-current-filename="@Model.UploadedFileName"></div>
            <input id="@controlId" name="@(controlId)-file" type="hidden" class="hidden" data-fileupload="true" value="@Model.UploadedFileGuid" />
            <div class="fu-controls">
            <file-uploader
                file-uploader-name="@clientId"
                upload-url="@Model.GetFileUploadUrl(Url)"
                display-browse-media-button="false"
                type-filter="@allowedFileExtensions"
                display-remove-button="@Model.UploadedFileGuid.HasValue()"
                display-remove-button-after-upload="true"
                upload-text="@T("Common.FileUploader.Upload")"
                onuploadcompleted="@("onFileUploaded" + clientId)"
                onfileremoved="@("onFileRemoved" + clientId)"
                multi-file="false"
                has-template-preview="true"
                download-enabled="true" />
        </div>
        </div>

        <div class="fu-progress">
            <!-- The single upload progress bar -->
            <div class="progress">
                <div class="progress-bar" role="progressbar" style="width: 0%" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
        </div>
    </div>
</div>

<script data-origin="choice-template">
    window['onFileUploaded@(clientId)'] = function (file, result, progress) {
        if (result.success && result.downloadGuid) {
            setUploadedFile(result.downloadGuid, file.name, "@(containerId)");
            displayNotification(result.message, "success");
        }
	};

    window['onFileRemoved@(clientId)'] = function (e, el) {
        $('#@containerId .hidden').val('');
    }

    function setUploadedFile(downloadGuid, fileName, containerId) {
        if (!_.isEmpty(downloadGuid) && downloadGuid !== '0') {
            $('#' + containerId + ' .hidden').val(downloadGuid);

        	var downloadLink = "@storeUrl" + "download/getfileupload/?downloadId=" + downloadGuid;
        	var fileLink = '<a href="' + downloadLink + '" class="fileuploadattribute" rel="nofollow">' + fileName + '</a>';

            $('#' + containerId + ' .fu-message').html(fileLink);
        }
    }
</script>
